<?php
gatekeeper ();
$DEFAULT = "";
elgg_make_sticky_form ( 'editprojects' );

$project_guid = get_input ( "project_guid", $DEFAULT );
$group_guid = get_input ( "group_guid", $DEFAULT );
$name = get_input ( "name", $DEFAULT );
$desp = get_input ( "descp", $DEFAULT );
$max_group = get_input ( "max_group", 0 );
$deadline = get_input ( "deadline", 0 );
$max_student = get_input ( "max_student", 0 );
$min_student = get_input ( "min_student", 0 );

$total_member = get_input ( 'total_member', $DEFAULT );

$listproj_url = elgg_get_site_url () . "submana/listpro/$group_guid";
if ($name != $DEFAULT && $max_group != 0 && $max_student != 0 && $min_student != 0) {
	$project = get_entity ( $project_guid );
	if ($project) {
		$project->title = $name;
		$project->max_group = $max_group;
		$project->description = $desp;
		$project->deadline = $deadline;
		$project->min_student = $min_student;
		$project->max_student = $max_student;
		
		$projectlist = get_entity ( $project->projectlist_guid );
		if ($projectlist) {
			
			$ar_groupproject = explode ( ",", $projectlist->group_project );
			$ar_deadline = explode ( ",", $projectlist->deadline );
			$ar_deadline_editted = explode ( ",", $projectlist->deadline_editted );
			
			for($i = 0; $i < count ( $ar_groupproject ); $i ++) {
				if ($ar_groupproject [$i] == $project->group_project) {
					$old_deadline = $ar_deadline [$i];
					if ($old_deadline != $deadline) {
						$ar_deadline_editted [$i] = "1";
					}
					break;
				}
			}
			
			$str = $ar_deadline_editted [0];
			for($i = 1; $i < count ( $ar_deadline_editted ); $i ++) {
				$str .= "," . $ar_deadline_editted [$i];
			}
			
			$projectlist->deadline_editted = $str;
		}
	}
	
	if ($total_member != $DEFAULT) {
		$members = array ();
		$j = 0;
		$is_error = false;
		for($i = 0; $i < $total_member; $i ++) {
			// add student to project
			$student_id = get_input ( "member" . ($i + 1), $DEFAULT );
			
			if ($student_id != $DEFAULT) {
				
				$student = get_user_by_username ( $student_id );
				if ($student) {
					array_push ( $members, "$student->username" );
					$j ++;
				} else {
					$is_error = true;
					register_error ( elgg_echo ( 'submana:project:noneuser', array (
							"$student_id" 
					) ) );
					// forward ( REFERER );
					exit ();
				}
			}
		}
		
		if (! $is_error) {
			$project->students = $members;
		}
	}
	
	$project->save ();
	system_message ( elgg_echo ( 'submana:message:editsuccess' ) );
	forward ( $listproj_url );
} else {
	register_error ( elgg_echo ( 'submana:message:failded' ) );
	forward ( REFERER );
}

elgg_clear_sticky_form ( 'editprojects' );